/************************************************************************************/
/*  Program name CAPGLIMP_SECURITY_RULE.sql                                        	*/
/*  Creater:  NIP Karen (PCCW - UniHub)                                         	*/
/*************   History   *************************                                */
/* 23 JAN, 2006   NIP Karen         First created                                   */
/************************************************************************************/
SET SERVEROUTPUT ON SIZE 1000000;

ALTER TRIGGER FND_FLEX_VALUE_RULES_CT1 DISABLE;

DECLARE
	lv_Prog_ID		VARCHAR2(100)	:=	'CAPGLIMP_SECURITY_RULE';

	lv_Scc_Count	NUMBER	:=	0;
	lv_Err_Count	NUMBER	:=	0;
	lv_Err_Msg		VARCHAR2(500)	:=	'No Error';

	CURSOR Cur_F IS
	SELECT
		*
	FROM
		CRST_FND_FLEX_VALUE_RULES;
	
	CURSOR Cur_C IS
	SELECT
		FVR.*
	FROM
		CFND_FLEX_VALUE_RULES			FVR,
		CRST_FND_FLEX_VALUE_RULES_MAP	FFV
	WHERE
		FVR.FLEX_VALUE_RULE_ID = FFV.FLEX_VALUE_RULE_ID;
		
	lv_Next_Seq_ID		NUMBER;
	
BEGIN

	
	FOR C1 IN Cur_F LOOP
		BEGIN
			SELECT	FND_FLEX_VALUE_RULES_S.NextVal
			INTO	lv_Next_Seq_ID
			FROM	DUAL;

			INSERT	INTO CRST_FND_FLEX_VALUE_RULES_MAP	VALUES
			(
			C1.flex_value_rule_id,
			CAPBRIMP_MAPPING.RenameStr(SUBSTR(C1.FLEX_VALUE_RULE_NAME,1,4), C1.FLEX_VALUE_RULE_NAME),
			C1.flex_value_set_id,
			C1.parent_flex_value_low,
			lv_Next_Seq_ID,
			C1.flex_value_rule_name,
			CAPBRIMP_MAPPING.GetFNDValueSetIDMapping(C1.flex_value_set_id),
			C1.parent_flex_value_low
			);
			
			INSERT INTO FND_FLEX_VALUE_RULES
			VALUES
			(
			lv_Next_Seq_ID,
			C1.flex_value_rule_name,
			CAPBRIMP_MAPPING.GetFNDValueSetIDMapping(C1.flex_value_set_id),
			C1.last_update_date,
			CAPBRIMP_COMMON.GetUser(C1.LAST_UPDATED_NAME),
			C1.creation_date,
			CAPBRIMP_COMMON.GetUser(C1.CREATED_NAME),
			C1.last_update_login,
			C1.parent_flex_value_low,
			C1.parent_flex_value_high
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;
	
	FOR C2 IN Cur_C LOOP
		BEGIN
			INSERT INTO CFND_FLEX_VALUE_RULES
			VALUES
			(
			CAPBRIMP_MAPPING.GetFNDValueRuleIDMapping(C2.FLEX_VALUE_RULE_ID),
			CAPBRIMP_MAPPING.GetOrgMapping(C2.S_ORG_ID),
			CAPBRIMP_MAPPING.GetBGMapping(C2.S_BUSINESS_GROUP_ID)
			);
		EXCEPTION
			WHEN OTHERS THEN
				DBMS_OUTPUT.Put_Line(SQLERRM);
				lv_Err_Count	:=	lv_Err_Count + 1;
		END;
		lv_Scc_Count	:=	lv_Scc_Count	+	1;
	END LOOP;
	
	IF	lv_Err_Count	>	0	THEN
		ROLLBACK;
	END IF;

	INSERT INTO CAPCNV_LOG(
		PROG_ID,
		PROCESS_DATE,
		RECORD_PROCESSED,
		RECORD_REJECTED,
		RECORD_EXTRACTED,
		ERR_MSG
	) VALUES (
		lv_Prog_ID,
		SYSDATE,
		lv_Scc_Count,
		lv_Err_Count,
		lv_Scc_Count-lv_Err_Count,
		lv_Err_Msg
	);
	
	COMMIT;
END;
/

ALTER TRIGGER FND_FLEX_VALUE_RULES_CT1 ENABLE;